package com.android.manghe.mine.activity;

import static com.pay.paytypelibrary.base.PayUtil.PAY_CODE;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.base.frame.view.MVPActivity;
import com.android.base.tools.DisplayUtil;
import com.android.base.tools.ToastUtil;
import com.android.base.view.roundview.RoundFrameLayout;
import com.android.base.view.roundview.RoundLinearLayout;
import com.android.manghe.R;
import com.android.manghe.box.model.PayWayModel;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.activity.PayFailActivity;
import com.android.manghe.common.activity.PaySuccessActivity;
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes;
import com.android.manghe.common.model.PaymentTypeRes;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.SimpleWebViewActivity;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.events.RefreshMemberInfoEvent;
import com.android.manghe.coupon.model.CouponRes;
import com.android.manghe.index.model.MainTopBannerBean;
import com.android.manghe.market.view.ConfirmPayResultDialog;
import com.android.manghe.mine.adapter.IntegralCoverPagerAdapter;
import com.android.manghe.mine.adapter.PayAdapter;
import com.android.manghe.mine.adapter.PriceAdapter;
import com.android.manghe.mine.model.SandPayH5Model;
import com.android.manghe.mine.model.SandPayModel;
import com.android.manghe.mine.presenter.PTopUp;
import com.android.manghe.quickpay.activity.QuickPayDetailActivity;
import com.android.manghe.view.dialog.NewTipDialog;
import com.eightbitlab.rxbus.Bus;
import com.pay.paytypelibrary.base.OrderInfo;
import com.pay.paytypelibrary.base.PayUtil;
import com.tmall.ultraviewpager.UltraViewPager;
import com.unionpay.UPPayAssistEx;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * author : liuwen
 * e-mail : liuwen370494581@163.com
 * time   : 2021/10/21 14:49
 * desc   : 充值页面
 */
public class TopUpActivity extends MVPActivity<PTopUp> {

    public static final int UNION_CODE = 10;
    private static final String TAG = TopUpActivity.class.getSimpleName();
    //对接杉德支付所需要的参数
    private RecyclerView mPriceRecyclerView, mPayRecyclerView;
    private TextView mTvPrice, mTvCoin, mTvBuy, mTvMustRead;
    private PayAdapter mPayAdapter;
    private PriceAdapter mPriceAdapter;
    private EditText mEditMoney;
    private RoundFrameLayout mLayoutEdit;
    private Double mCurrentPrice = 0.00;//当前价格
    private String mCouponId = "";
    private int mCurrentAccount = 1;//数量 默认就是1;
    private CouponRes.DataBean.CouponInfo mOneCouponInfo;
    private LinearLayout mLayoutMustRead;
    private RoundLinearLayout mLayoutPayMent;
    private LinearLayout mLayoutBody;

    private UltraViewPager mViewpager;
    private IntegralCoverPagerAdapter mPagerAdapter;


    @Override
    public int getLayoutId() {
        return R.layout.activity_top_up;
    }

//    @Override
//    protected ETitleType showToolBarType() {
//        return ETitleType.OVERLAP_TITLE;
//    }


    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {

        getTitleBar().setToolbar("充值中心").setLeftIcon(R.mipmap.icon_back_black).hideBottomLine().setBackgroundColor(ContextCompat.getColor(mContext, R.color.white));
        mPayRecyclerView = findViewById(R.id.id_pay_recycler_view);
        mPriceRecyclerView = findViewById(R.id.id_price_recycler_view);
        mTvPrice = findViewById(R.id.tvTotalPrice);
        mTvCoin = findViewById(R.id.tvCoin);
        mTvBuy = findViewById(R.id.tvOriginalBuy);
        mEditMoney = findViewById(R.id.id_edit_money);
        mLayoutEdit = findViewById(R.id.id_layout_edit);
        mTvMustRead = findViewById(R.id.id_tv_must_read);
        mLayoutMustRead = findViewById(R.id.id_ly_must_read);
        mLayoutPayMent = findViewById(R.id.id_ly_pay_ment);
        mLayoutBody = findViewById(R.id.id_ly_body);
        mViewpager = findViewById(R.id.id_view_pager);

        initRecyclerView();
        setListener();
        getP().getPaymentType();
        getP().getCoupon();
        getP().getBanner();

    }


    public double getMCurrentPrice() {
        return mCurrentPrice;
    }

    private void setListener() {
        mTvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toTopUp();
            }
        });

        mPayAdapter.setListener(new PayAdapter.IPayListener() {
            @Override
            public void onClick(PaymentTypeRes.DataBean.PaymentBean item) {
                mPayAdapter.selectedItem(item);
            }
        });
        mPriceAdapter.setListener(new PriceAdapter.IPriceListener() {
            @Override
            public void onClick(CouponRes.DataBean.CouponInfo item, int position) {
                mPriceAdapter.selectedItem(item);
                dealPriceCoin();
                mEditMoney.setText("");
            }
        });

        mEditMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPriceAdapter.selectedItem(null);
                mEditMoney.setText("");
                mCurrentAccount = 0;
                mTvPrice.setText("00.00");
                mTvCoin.setText("共赠送0币");
            }
        });
        mEditMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (!TextUtils.isEmpty(mEditMoney.getText().toString())) {
                        mPriceAdapter.selectedItem(null);
                        mCurrentPrice = Double.parseDouble(mEditMoney.getText().toString());
                        mTvPrice.setText(mCurrentPrice + "");
                        mTvCoin.setText("共赠送0币");
                    }
                } catch (java.lang.Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void dealPriceCoin() {
        CouponRes.DataBean.CouponInfo couponInfo = mPriceAdapter.getSelectedCoupon();
        if (couponInfo != null) {
            mTvPrice.setText(couponInfo.price);
            mTvCoin.setText("共赠送" + couponInfo.free_coin + "币");
        } else {
            mTvPrice.setText(mCurrentPrice + "");
            mTvCoin.setText("共赠送0币");
        }
    }

    private void toTopUp() {
        String money = mEditMoney.getText().toString().intern();
        CouponRes.DataBean.CouponInfo couponInfo = mPriceAdapter.getSelectedCoupon();
        PaymentTypeRes.DataBean.PaymentBean paymentBean = mPayAdapter.getSelectedPayment();

        if (mOneCouponInfo != null && mLayoutEdit.getVisibility() == View.VISIBLE) {
            if (couponInfo != null) {
                //有输入框 但是选择了其他卷
                mCouponId = couponInfo.id;
                mCurrentAccount = 1;
                getP().getOrderMsg(mCouponId, mCurrentAccount + "", paymentBean.pay_id, paymentBean.pay_code);
            } else {
                //有输入框，但选择了输入
                if (TextUtils.isEmpty(money)) {
                    ToastUtil.showShort(this, "请输入金额");
                    return;

                }

                if (Integer.parseInt(money) < 10) {
                    ToastUtil.showShort(this, "最少充值10元");
                    return;
                }

                if (Integer.parseInt(money) > 999) {
                    ToastUtil.showShort(this, "最多充值999元");
                    return;
                }

                mCouponId = mOneCouponInfo.id;
                mCurrentAccount = Integer.parseInt(money);


                getP().getOrderMsg(mCouponId, mCurrentAccount + "", paymentBean.pay_id, paymentBean.pay_code);
            }
        } else {
            //没有输入框
            if (couponInfo == null) {
                ToastUtil.showLong(getApplicationContext(), "请选择充值金额");
                return;
            }

            mCouponId = couponInfo.id;
            mCurrentAccount = 1;
            getP().getOrderMsg(mCouponId, mCurrentAccount + "", paymentBean.pay_id, paymentBean.pay_code);
        }


    }


    private void initRecyclerView() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mPriceRecyclerView.setLayoutManager(gridLayoutManager);
        mPayRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mPayAdapter = new PayAdapter(this, new ArrayList<>());
        mPriceAdapter = new PriceAdapter(this, new ArrayList<>());
        mPriceRecyclerView.setAdapter(mPriceAdapter);
        mPayRecyclerView.setAdapter(mPayAdapter);
    }


    /**
     * 更新充值的封面图
     *
     * @param bannerList
     */
    public void updateBanner(List<MainTopBannerBean> bannerList) {
        mPagerAdapter = new IntegralCoverPagerAdapter(this, bannerList);
        mViewpager.setAdapter(mPagerAdapter);
        if (bannerList.size() > 1) {
            mViewpager.setInfiniteLoop(true);
            mViewpager.setAutoScroll(5000);
            mViewpager.setCurrentItem(0);
            mViewpager.initIndicator()
                    .setOrientation(UltraViewPager.Orientation.HORIZONTAL)
                    .setFocusColor(ContextCompat.getColor(mContext, R.color.orange300))
                    .setNormalColor(ContextCompat.getColor(mContext, R.color.grey200))
                    .setRadius(DisplayUtil.dip2px(mContext, 4f)).setMargin(0, 0, 0, DisplayUtil.dip2px(mContext, 20))
                    .setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM)
                    .build();
        } else {
            mViewpager.disableIndicator();
            mViewpager.setInfiniteLoop(false);
        }
    }


    /**
     * 更新卷
     *
     * @param couponInfos
     */
    public void updateData(List<CouponRes.DataBean.CouponInfo> couponInfos) {
        mPriceAdapter.update(sort(couponInfos));
        if (mOneCouponInfo != null) {
            mLayoutEdit.setVisibility(View.VISIBLE);
            mCouponId = mOneCouponInfo.id;
        } else {
            mLayoutEdit.setVisibility(View.GONE);
        }
        dealPriceCoin();
    }

    public void updateMustRead(String desc) {
        mLayoutMustRead.setVisibility(View.VISIBLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mTvMustRead.setText(Html.fromHtml(desc, Html.FROM_HTML_MODE_COMPACT));
        } else {
            mTvMustRead.setText(Html.fromHtml(desc));
        }
    }

    /**
     * 如果是id==99的卷 则有输入框
     *
     * @param couponInfos
     * @return
     */
    private List<CouponRes.DataBean.CouponInfo> sort(List<CouponRes.DataBean.CouponInfo> couponInfos) {
        List<CouponRes.DataBean.CouponInfo> list = new ArrayList<>();
        for (CouponRes.DataBean.CouponInfo info : couponInfos) {
            if (info.id.equals("99")) {
                mOneCouponInfo = info;
            } else {
                list.add(info);
            }
        }
        return list;

    }

    /**
     * 更新支付方式
     *
     * @param payment
     */
    public void updatePayments(List<PaymentTypeRes.DataBean.PaymentBean> payment) {
        mLayoutPayMent.setVisibility(View.VISIBLE);
        mPayAdapter.update(payment);
    }

    public void showTipPopWindow(String desc, int code) {
        if(!TopUpActivity.this.isFinishing()){
            NewTipDialog dialog = new NewTipDialog(this, desc);
            dialog.show();
            dialog.setListener(new NewTipDialog.ITipDialogListener() {
                @Override
                public void clickLeft() {

                }

                @Override
                public void clickRight() {
                    switch (code) {
                        case 1:
                            getP().getCoupon();
                            break;
                        case 2:
                            getP().getPaymentType();
                            break;
                    }
                }
            });
        }
    }

    public void onBack(View view) {
        finish();
    }


    public void openQuickPay(BuyMemberShangMengZhiFuRes.DataBean buyMemberShangMengZhiFuData) {
        Intent intent = new Intent(this, QuickPayDetailActivity.class);
        intent.putExtra("buyMemberShangMengZhiFuData", buyMemberShangMengZhiFuData);
        startActivityForResult(intent, 2000);
    }

    public void payFail() {
        ToastUtil.showShort(this, "未完成支付");
    }

    public void paySuccess() {
        open(PaySuccessActivity.class);
        Bus.INSTANCE.send(new RefreshMemberInfoEvent());
        finish();
    }

    public void payFailAy() {
        open(PayFailActivity.class);
        finish();

    }

    public void toPayByH5(String url) {
        Intent intent = new Intent(this, SimpleWebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", "支付");
        startActivity(intent);
    }

    public void toPayByBrowser(String url, String orderId) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);
        //弹出让用户确定是否支付成功的弹出框
        if (orderId != null) {
            ConfirmPayResultDialog dialog = new ConfirmPayResultDialog(this, orderId, new ConfirmPayResultDialog.CallBack() {
                @Override
                public void callBack(String orderId) {
                    Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                }
            });
            dialog.show();
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null && data.getExtras() != null && data.getExtras().getBoolean("fail", false)) {
                finish();
                open(PayFailActivity.class);
                Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                return;
            }
            if (requestCode == 1000 || requestCode == 2000) {
                if (data != null && data.getExtras() != null && data.getExtras().getBoolean("fail", false)) {
                    finish();
                    open(PayFailActivity.class);
                    Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                    return;
                }
                //翼支付、快捷支付 成功支付
                finish();
                open(PaySuccessActivity.class);
                Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                return;
            }


            //对接杉德支付里的银行银联支付=========================================================
            if (requestCode == PAY_CODE) {
                OrderInfo orderInfo = (OrderInfo) data.getSerializableExtra("orderInfo");
                if (orderInfo != null) {
                    if (!TextUtils.isEmpty(orderInfo.getTradeNo())) {
                        startUnionpay(TopUpActivity.this, orderInfo.getTradeNo());
                        Bus.INSTANCE.send(new RefreshMemberInfoEvent());
                        return;
                    }
                }
            }
            if (requestCode == UNION_CODE) {
                Bundle bundle = data.getExtras();
                if (null == bundle) {
                    return;
                }
                /*
                 * 支付控件返回字符串:
                 * success、fail、cancel 分别代表支付成功，支付失败，支付取消
                 */
                Log.e(TAG, "onActivityResult");
                getP().setOut_trade_no(null);
                String result = bundle.getString("pay_result");
                if (result != null) {
                    Intent intent = null;
                    if (result.equalsIgnoreCase("success")) {
                        intent = new Intent(this, PaySuccessActivity.class);
                        startActivity(intent);
                    } else if (result.equalsIgnoreCase("fail")) {
                        intent = new Intent(this, PayFailActivity.class);
                        startActivity(intent);
                    } else if (result.equalsIgnoreCase("cancel")) {
                        ToastUtil.showLong(this, "您已取消支付");
                    }
                }

            }
        }
    }


    //===============================================================对接珊德宝支付======================================
    public void cashierPay(SandPayModel.Data sandPayModel) {
        JSONObject orderJson = new JSONObject();
        try {
            getP().setOut_trade_no(sandPayModel.order.outTradeNo);
            orderJson.put("version", sandPayModel.paycode.version);
            orderJson.put("sign_type", sandPayModel.paycode.signType);
            orderJson.put("mer_no", sandPayModel.paycode.merNo); // 商户编号
            orderJson.put("mer_key", sandPayModel.paycode.merKey); // 商户密钥
            orderJson.put("mer_order_no", sandPayModel.paycode.merOrderNo); // 商户订单号
            orderJson.put("create_time", sandPayModel.paycode.createTime); // 订单创建时间
            orderJson.put("expire_time", sandPayModel.paycode.expireTime); // 订单失效时间
            orderJson.put("order_amt", sandPayModel.paycode.orderAmt); // 订单金额
            orderJson.put("notify_url", sandPayModel.paycode.notifyUrl); // 回调地址
            orderJson.put("return_url", sandPayModel.paycode.returnUrl);//"http://www.baidu.com"); // 支付后返回的商户显示页面
            orderJson.put("create_ip", sandPayModel.paycode.createIp); // 客户端的真实IP
            orderJson.put("goods_name", sandPayModel.paycode.goodsName); // 商品名称
            orderJson.put("store_id", sandPayModel.paycode.storeId); // 门店号
            orderJson.put("product_code", sandPayModel.paycode.productCode); // 支付产品编码
            orderJson.put("clear_cycle", sandPayModel.paycode.clearCycle); // 清算模式
            orderJson.put("accsplit_flag", sandPayModel.paycode.accsplitFlag); // 分账标识 NO无分账，YES有分账
            orderJson.put("sign", sandPayModel.paycode.sign);//签名
            orderJson.put("pay_extra", sandPayModel.paycode.payExtra);
            orderJson.put("jump_scheme", "topcash://toppay"); // 支付宝返回app所配置的域名
            // orderJson.put("limit_pay", ""); //微信传1屏蔽信用卡，支付宝传5屏蔽部分信用卡以及花呗，支付宝传4屏蔽花呗，支付宝传1屏蔽部分信用卡，银联不支持屏蔽   不参与签名
        } catch (Exception e) {
            e.getStackTrace();
        }
        PayUtil.CashierPay(TopUpActivity.this, orderJson.toString());
    }

    public void cashierPayH5(SandPayH5Model.Data sandPayH5model) {
        getP().setOut_trade_no(sandPayH5model.order.outTradeNo);
        WebViewParameter parameters = new WebViewParameter.WebParameterBuilder()
                .setHtmlUrl(sandPayH5model.paycode.body.credential)
                .setShowProgress(true)
                .setCanHistoryGoBackOrForward(true)
                .setReloadable(true)
                .setShowWebPageTitle(false)
                .setReloadType(ERefreshWebType.ClickRefresh)
                .setCustomTitle("快捷支付")
                .build();
        Intent intent = new Intent(mContext, WebViewActivity.class);
        intent.putExtra("parameters", parameters);
        startActivity(intent);

    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        Uri uri = intent.getData();
//        Log.e(TAG, "onNewIntent");
//        if (uri != null) {
//            Intent payIntent = null;
//            String payCode = uri.getQueryParameter("payCode");  // 支付宝支付完后返回app后 所传的code
//            Log.e(TAG, "payCode:" + payCode); //  2为成功
//            assert payCode != null;
//            if (payCode.equals("2")) {
//                payIntent = new Intent(mContext, PaySuccessActivity.class);
//            } else {
//                payIntent = new Intent(mContext, PayFailActivity.class);
//            }
//            startActivity(payIntent);
//        }
//    }

    /**
     * 银联云闪付
     */
    public void startUnionpay(Context context, String tradeNo) {
        UPPayAssistEx.startPay(context, null, null, tradeNo, "00");
    }

    public void showPayWay(PayWayModel.Data paWayModel) {
        if (paWayModel.payType.equals("6")) {
            //6表示充值订单
            if (paWayModel.payWay == null) {
                return;
            }
            if (paWayModel.payWay.equals("0") || paWayModel.payWay.equals("1") || paWayModel.payWay.equals("2")) {
                //表示只有支付宝 和杉德支付宝的时候才调用
                getP().setOut_trade_no(null);
                if (paWayModel.isPaid.equals("1")) {
                    paySuccess();
                } else {
                    payFail();
                }
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "onResume");
        if (getP().getOut_trade_no() != null && UserHolder.getUserInfo(this) != null) {
            getP().getPayWay();
        }
    }


}
